package cms.simmytech.service;

import cms.simmytech.mapper.TbCategoryMapper;
import cms.simmytech.mapper.TbContentMapper;
import cms.simmytech.mapper.TbContentMapper;
import cms.simmytech.model.TbCategory;
import cms.simmytech.model.TbContent;
import cms.simmytech.model.TbContentExample;
import cms.simmytech.model.TbContent;
import cms.simmytech.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentService {
    @Autowired
    private TbContentMapper mapper;
    @Autowired
    private TbCategoryMapper categoryMapper;
    public PageInfo<TbContent> getPageList(Integer pageNum, Integer pageSize, String name, Byte contentType, Integer cateId) {
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        //对标题名称进行处理--便于模糊查询
        if(!"".equals(name)&&null!=name){
            criteria.andTitleNameLike("%"+name+"%")	;
        }
        if (contentType!=-99){
            criteria.andContentTypeEqualTo(contentType);
        } if (cateId!=-99){
            criteria.andCateIdEqualTo(cateId);
        }
        //根据contentId进行降序
        example.setOrderByClause("content_id  desc");
        PageHelper.startPage(pageNum, pageSize);
        List<TbContent> list = mapper.selectByExample(example);
        PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(list);
        return pageInfo;
    }

    public TbContent getBean(Integer id) {
        return  mapper.selectByPrimaryKey(id);
    }

    public void save(TbContent bean) {
        bean.setCateName(categoryMapper.selectByPrimaryKey(bean.getCateId()).getCateName());
        //对Id进行判断：id为null证明是添加，否则为更新
        if (bean.getContentId()== null) {
            Integer now = DateUtil.getIntStampTime();
            bean.setCreateTime(now);
            mapper.insertSelective(bean);

        } else {
            mapper.updateByPrimaryKeySelective(bean);
        }
    }

    public void delete(int id) {
        mapper.deleteByPrimaryKey(id);
    }

    public PageInfo<TbContent> getContentList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        TbContentExample example=new TbContentExample();
        example.setOrderByClause(" content_id  desc");
        List<TbContent> list= mapper.selectByExample(example);
        PageInfo<TbContent> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }



    public void deleteContent(int id) {
        mapper.deleteByPrimaryKey(id);
    }
    public void AddContent(TbContent tbContent){
        mapper.insert(tbContent);
    }

    public TbContent getContentByContentID(int contentId){
        return mapper.selectByPrimaryKey(contentId);
    }
    public void updateContentByContentId(TbContent tbContent){
        mapper.updateByPrimaryKey(tbContent);
    }
}
